package com.dna.service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dna.entity.DepartEntity;
import com.dna.entity.MenuEntity;
import com.dna.mapper.DepartMapper;
import com.dna.service.DepartService;
import com.dna.utils.Constant.UserState;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

@Service
public class DepartServiceImpl implements DepartService {

    @Autowired
    private DepartMapper departMapper;

    @Override
    public List<DepartEntity> queryAll() {
        List<DepartEntity> deptList = buildDeptTree(departMapper.queryList(), 0L);
        
        return deptList;
    }

    public List<DepartEntity> buildDeptTree(List<DepartEntity> list, Long id) {
        List<DepartEntity> subDeptList = Lists.newArrayList();

        for (DepartEntity dept : list) {
            if (id == dept.getParentId()) {
                dept.setChildren(buildDeptTree(list, dept.getId()));
                subDeptList.add(dept);
            }
        }
        return subDeptList;
    }

    @Override
    public DepartEntity queryOne(DepartEntity dep) {
        return departMapper.selectOne(dep);
    }

    @Override
    @Transactional
    public void save(DepartEntity dep) {
        departMapper.insertSelective(dep);

    }

    @Override
    @Transactional
    public void update(DepartEntity dep) {
        departMapper.updateByPrimaryKeySelective(dep);

    }

    @Override
    public void delete(Set<Long> ids) {
        DepartEntity record = new DepartEntity();
        record.setState(UserState.NORMAL.getValue());
        List<DepartEntity> deptList = departMapper.select(record);

        Set<Long> deptSet = Sets.newHashSet(ids);
        deptSet = getDeptIds(deptList, ids, deptSet);

        Example example = new Example(MenuEntity.class);
        Criteria criteria = example.createCriteria();
        criteria.andIn("id", deptSet);
        DepartEntity record1 = new DepartEntity();
        record1.setState(UserState.DELETE.getValue());
        departMapper.updateByExampleSelective(record1, example);

    }

    private Set<Long> getDeptIds(List<DepartEntity> deptList, Set<Long> ids, Set<Long> deptSet) {
        if (ids.isEmpty()) {
            return deptSet;
        }
        Set<Long> startIds = new HashSet<>(ids);
        for (Long id : ids) {
            for (DepartEntity dept : deptList) {
                if (id.intValue() == dept.getParentId().intValue()) {
                    deptSet.add(dept.getId());
                    startIds.add(dept.getId());
                }
            }
            startIds.remove(id);
        }
        return getDeptIds(deptList, startIds, deptSet);
    }

}
